"use strict";
import '../plugin/need/popup.scss';
import { queryAll } from '../utils/dom-query';
import { isPlainObject } from '../utils/is-plain-object';
import { extend } from '../utils/extend';

/**
 * 合法化一个值
 * @param {*} target 目标值 
 * @returns 返回一个 
 */
function legalize(target) {
  switch (typeof target) {
    case 'number': return isNaN(target) ? 0 : target;
    case 'boolean': return target ? 1 : 0;
    case 'string': return target;
    case 'symbol':
    case 'object':
    case 'undefined':
    case 'function':
    default: return '';
  }
}

function layout(opts) {
  // 缓存
  const id = toNumber(opts.id);

  // 与布局相关
  const popupID = legalize(opts.popup); // 弹层的唯一标识
  const shadeID = legalize(opts.shade); // 弹层的阴影遮罩层
  const zIndex = legalize(opts.index); // z-index


  const hasShade = Boolean(shadeID); // 是否加载阴影遮罩层

  return `\
  <div id="${popupID}" class="popup${mainClass !== '' ? ' ' + mainClass : ''}" data-index="${zIndex}">\
    <div class="popup-scope">
    </div>
    <div class="popup-group">\

    </div>\ 
  </div>\
  ${hasShade ? `<div id="${shadeID}" class="shade${maskClass !== '' ? ' ' + maskClass : ''}"></div>` : ''}`;
}

layout.cache = {};

/**
 * HTML5 WAP 弹层插件 
 * 
 * @constructor 
 * 
 * --------------------------------------------------------- 配置项 1️⃣
 * @param {number}  options.type 默认: 0
 * @param {boolean} options.shade 默认: true
 * @param {boolean} options.shadeClose 默认: true
 * @param {boolean} options.fixed 默认: true
 * @param {string}  options.anim 动画类型, CSS3动画, 默认: scale
 *
 * --------------------------------------------------------- 成员方法、属性
 * @method view
 * @method action
 * @method open
 * @method close
 * @method closeAll
 * 
 * --------------------------------------------------------- 静态方法、属性
 * @property {object} DEFAULT 引用了 Popup 类的配置项，详情请看 1️⃣
 * @property {number} index 存储 Popup 类的最后一个实例的索引值，当 Popup 实例存在多个时，index值会累加，表明了多个弹层的层叠顺序【后来者居上】
 * 
 **/
export class Popup {
  constructor(options) {
    this.config = isPlainObject(options) ? Popup.DEFAULT : extend({}, Popup.DEFAULT, options);

    this.view();
  }

  /**
   * 生成HTML结构并添加到文档中，绑定事件
   * 
   * @example 一个标准的 popup HTML结构 :
   *    <div class="popup ${animation} ${theme} ${size}">
   *      <div></div>
   *    </div>
   * 
   * @memberOf 
   **/
  view() {
    var that = this, config = that.config, layerbox = document.createElement('div');
    that.id = layerbox.id = classs[0] + index;
    layerbox.setAttribute('class', classs[0] + ' ' + classs[0] + (config.type || 0));
    layerbox.setAttribute('index', index);

    //标题区域
    var title = (function () {
      var titype = typeof config.title === 'object';
      return config.title
        ? '<h3 style="' + (titype ? config.title[1] : '') + '">' + (titype ? config.title[0] : config.title) + '</h3>'
        : '';
    }());

    //按钮区域
    var button = (function () {
      typeof config.btn === 'string' && (config.btn = [config.btn]);
      var btns = (config.btn || []).length, btndom;
      if (btns === 0 || !config.btn) {
        return '';
      }
      btndom = '<span yes type="1">' + config.btn[0] + '</span>';
      if (btns === 2) {
        btndom = '<span no type="0">' + config.btn[1] + '</span>' + btndom;
      }
      return '<div class="layui-m-layerbtn">' + btndom + '</div>';
    }());
    if (!config.fixed) {
      config.top = config.hasOwnProperty('top') ? config.top : 100;
      config.style = config.style || '';
      config.style += ' top:' + (document.body.scrollTop + config.top) + 'px';
    }
    if (config.type === 2) {
      config.content = '<i></i><i class="layui-m-layerload"></i><i></i><p>' + (config.content || '') + '</p>';
    }
    if (config.skin)
      config.anim = 'up';
    if (config.skin === 'msg')
      config.shade = false;
    layerbox.innerHTML = (config.shade ? '<div ' + (typeof config.shade === 'string' ? 'style="' + config.shade + '"' : '') + ' class="layui-m-layershade"></div>' : '')
      + '<div class="layui-m-layermain" ' + (!config.fixed ? 'style="position:static;"' : '') + '>'
      + '<div class="layui-m-layersection">'
      + '<div class="layui-m-layerchild ' + (config.skin ? 'layui-m-layer-' + config.skin + ' ' : '') + (config.className ? config.className : '') + ' ' + (config.anim ? 'layui-m-anim-' + config.anim : '') + '" ' + (config.style ? 'style="' + config.style + '"' : '') + '>'
      + title
      + '<div class="layui-m-layercont">' + config.content + '</div>'
      + button
      + '</div>'
      + '</div>'
      + '</div>';
    if (!config.type || config.type === 2) {
      var dialogs = document.getElementsByClassName(classs[0] + config.type), dialen = dialogs.length;
      if (dialen >= 1) {
        layer.close(dialogs[0].getAttribute('index'));
      }
    }
    document.body.appendChild(layerbox);
    var elem = that.elem = queryAll('#' + that.id)[0];
    config.success && config.success(elem);
    that.index = index++;
    that.action(config, elem);
  }

  action(config, elem) {
    var that = this;
    //自动关闭
    if (config.time) {
      ready.timer[that.index] = setTimeout(function () {
        layer.close(that.index);
      }, config.time * 1000);
    }

    //确认取消
    var btn = function () {
      var type = this.getAttribute('type');
      if (type == 0) {
        config.no && config.no();
        layer.close(that.index);
      }
      else {
        config.yes ? config.yes(that.index) : layer.close(that.index);
      }
    };

    if (config.btn) {
      var btns = elem.getElementsByClassName('layui-m-layerbtn')[0].children, btnlen = btns.length;
      for (var ii = 0; ii < btnlen; ii++) {
        ready.touch(btns[ii], btn);
      }
    }

    //点遮罩关闭
    if (config.shade && config.shadeClose) {
      var shade = elem.getElementsByClassName('layui-m-layershade')[0];
      ready.touch(shade, function () {
        layer.close(that.index, config.end);
      });
    }
    config.end && (ready.end[that.index] = config.end);
  }

  // 核心方法
  open(options) {
    var o = new Layer(options || {});
    return o.index;
  }

  close(index) {
    var ibox = queryAll('#' + classs[0] + index)[0];
    if (!ibox) return;
    ibox.innerHTML = '';
    doc.body.removeChild(ibox);
    clearTimeout(ready.timer[index]);
    delete ready.timer[index];
    typeof ready.end[index] === 'function' && ready.end[index]();
    delete ready.end[index];
  }

  // 关闭所有layer层
  closeAll() {
    var boxs = document.getElementsByClassName(classs[0]);
    for (var i = 0, len = boxs.length; i < len; i++) {
      layer.close((boxs[0].getAttribute('index') | 0));
    }
  }
}

// 默认配置
Popup.DEFAULT = {
  type: 0,
  shade: true,
  shadeClose: true,
  fixed: true,
  anim: 'scale'
}

Popup.index = 0;

Popup.ready = {
  timer: {},
  end: {},

  //点触事件
  touch: function (elem, fn) {
    elem.addEventListener('click', function (e) {
      fn.call(this, e);
    }, false);
  }
}

var config = Popup.DEFAULT;
var ready = Popup.ready;
var index = Popup.index,
  classs = ['layui-m-layer'];